package com.hxht.cmp.utils;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by alice on 2017/3/10 0010
 */
public class XmlUtils {
    private static Logger log = Logger.getLogger(XmlUtils.class);

    /**
     * 读取cfg，解析出isrecord的通道并返回isrecord=1的list
     *
     * @param str cfg的xml（string）
     * @return list
     */
    public static List<Map<String, String>> readRecord(String str, String devip) {
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new StringReader(str));
            Element root = document.getRootElement();
            Element el = root.element("EncodeManage");
            List<Map<String, String>> result = new ArrayList<>();
            if (el != null) {
                System.out.println(el.getName());
                List<Element> list = el.elements("encode");
                for (int i = 0; i < list.size(); i++) {
                    Map<String, String> temp = new HashMap<>();
                    temp.put("ip", devip);
                    temp.put("chnname", list.get(i).attributeValue("chnname"));
                    temp.put("encodeip", list.get(i).attributeValue("encodeip"));
                    temp.put("isrecord", list.get(i).attributeValue("isrecord"));
                    temp.put("index", String.valueOf(i+1));
                    result.add(temp);
                }
            }
            return result;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }
}
